// 显示提示信息
function showToast(message, type = 'none') {
  wx.showToast({
    title: message,
    icon: type
  })
}

// 显示加载提示
function showLoading(message = '加载中...') {
  wx.showLoading({
    title: message,
    mask: true
  })
}

// 隐藏加载提示
function hideLoading() {
  wx.hideLoading()
}

// 显示确认对话框
function showConfirm(title, content) {
  return wx.showModal({
    title,
    content,
    confirmText: '确认',
    cancelText: '取消'
  })
}

// 显示商品确认提示
export function showProductConfirm(product, quantity, specs, remark, action = '购买') {
  // 格式化规格文本
  const specsText = specs ? Object.entries(specs)
    .map(([key, value]) => `${key}:${value}`)
    .join('、') : ''

  // 查找对应规格组合的价格
  let price = product.price
  if (product.specCombos && specs) {
    const matchedCombo = product.specCombos.find(combo => 
      Object.entries(combo.specs).every(([key, value]) => specs[key] === value)
    )
    if (matchedCombo) {
      price = matchedCombo.price
    }
  }

  // 计算总价
  const totalAmount = (price * quantity).toFixed(2)

  return new Promise((resolve) => {
    wx.showModal({
      title: `确认${action}`,
      content: 
        `商品：${product.name}\n` +
        (specsText ? `规格：${specsText}\n` : '') +
        `数量：${quantity}\n` +
        `单价：¥${price}\n` +
        `总价：¥${totalAmount}\n` +
        (remark ? `备注：${remark}\n` : ''),
      confirmText: action,
      confirmColor: '#ff4d4f',
      success: (res) => {
        resolve({
          confirm: res.confirm,
          totalAmount: parseFloat(totalAmount)
        })
      },
      fail: () => {
        resolve({ confirm: false })
      }
    })
  })
}

// 选择收货地址
async function chooseAddress() {
  try {
    // 先尝试使用微信原生的地址选择器
    const res = await new Promise((resolve, reject) => {
      wx.chooseAddress({
        success: (res) => {
          resolve({
            name: res.userName,
            phone: res.telNumber,
            province: res.provinceName,
            city: res.cityName,
            district: res.countyName,
            detail: res.detailInfo
          })
        },
        fail: async (err) => {
          try {
            // 如果微信地址选择失败，则使用自定义地址列表
            const db = wx.cloud.database()
            const { data: addresses } = await db.collection('addresses')
              .where({
                userId: getApp().globalData.openid
              })
              .get()

            console.log('获取到的地址列表：', addresses)

            if (!addresses || addresses.length === 0) {
              const res = await wx.showModal({
                title: '提示',
                content: '您还没有收货地址，是否添加新地址？',
                confirmText: '添加地址',
                cancelText: '取消'
              })
              
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/address/edit'
                })
              }
              reject(new Error('请先添加收货地址'))
              return
            }

            // 如果只有一个地址，直接返回
            if (addresses.length === 1) {
              resolve(addresses[0])
              return
            }

            // 多个地址时，显示选择列表
            const { tapIndex } = await wx.showActionSheet({
              itemList: addresses.map(addr => 
                `${addr.name} ${addr.phone}\n${addr.province}${addr.city}${addr.district}${addr.detail}`
              )
            })

            resolve(addresses[tapIndex])
          } catch (error) {
            reject(error)
          }
        }
      })
    })

    return res
  } catch (error) {
    console.error('地址选择过程出错：', error)
    throw error
  }
}

// 配送方式枚举
const DELIVERY_TYPE = {
  DELIVERY: {
    value: 'delivery',
    desc: '需要配送'
  },
  SELF_PICKUP: {
    value: 'self_pickup',
    desc: '到店自提'
  }
}

// 选择配送方式
async function chooseDeliveryType() {
  const { tapIndex } = await wx.showActionSheet({
    itemList: [
      DELIVERY_TYPE.DELIVERY.desc,
      DELIVERY_TYPE.SELF_PICKUP.desc
    ]
  })
  
  return Object.values(DELIVERY_TYPE)[tapIndex]
}

module.exports = {
  showToast,
  showLoading,
  hideLoading,
  showConfirm,
  showProductConfirm,
  chooseAddress,
  chooseDeliveryType,
  DELIVERY_TYPE
} 